/* SharePoint Console Project
 * Http://SharePointConsole.codeplex.com
 * Copyright Jean-Alain Baeyens (2009)
 * Software under Microsoft Reciprocal License (Ms-RL)
 */

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.StsAdmin;
using System.Collections.Specialized;
using Sharepoint.Console.Commands;
using System.Reflection;


namespace Sharepoint.Console.StsAdm
{
    class StsAdmExtensionEncapsulation:BaseCommande
    {
        private object stsAdmCmd;
        private string cmdName;
        
        public StsAdmExtensionEncapsulation(string name, object cmd, bool recursive)
        {
            isRecursionAllowed = recursive;
            stsAdmCmd = cmd;
            cmdName = name;
        }

        public override string Execute(string[] args)
        {
            string output;
            StringDictionary parameters = new StringDictionary();
            for (int i=1; i<args.Length; i+=2)
            {
                parameters.Add(args[i],args[i+1]);
            }
            Type cmdType = stsAdmCmd.GetType();
            object[] param = { parameters };

            MethodInfo meth = cmdType.GetMethod("Run");
            if (meth != null)
            {
                output = "";
                try
                {
                    meth.Invoke(stsAdmCmd, param);
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        output = ex.InnerException.Message;
                    }
                    else
                    {
                        output = ex.Message;
                    }
                }
                return output;
            }
            else
            {
                return "Invalid command";
            }
        }

        public override string ShortHelp
        {
            get { 
                //return stsAdmCmd.GetHelpMessage(cmdName); 
                Type cmdType = stsAdmCmd.GetType();
                MethodInfo meth = cmdType.GetMethod("GetHelpMessage");
                if (meth != null)
                {
                    object[] param = { cmdName };
                    return (string)meth.Invoke(stsAdmCmd, param);
                }
                else
                {
                    return "Invalid command";
                }

            }
        }
    

    }
}
